package com.xwaf.platform.system.provider.serviceimpl.pay;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xwaf.platform.common.redis.GenSnHandler;
import com.xwaf.platform.system.api.entity.DataBase;
import com.xwaf.platform.system.api.entity.pay.Order;
import com.xwaf.platform.system.api.service.pay.PaymentService;
import com.xwaf.platform.system.api.service.pay.TccService;
import com.xwaf.platform.system.provider.dao.pay.OrderDao;

/**
 * <p>
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2020年1月15日 上午10:26:58 <br>
 * @see 无<br>
 *      Copyright (c) 2020, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Transactional(readOnly = true)
@Service("tccService")
public class TccServiceImpl implements TccService {

	@Autowired
	private OrderDao orderDao;

	@Autowired
	PaymentService paymentService;

	@Autowired
	GenSnHandler genSnHandler;

	@Override
	@Transactional(readOnly = false, isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean createOrder() {
		// 获取账户信息(余额等)
		String userId = DataBase.getDataBaseId(DataBase.UR);
		userId = "230";
		// 获取库存商品金额等
		Long stockPrice = 101L;
		// 比较余额和商品金额能否支付,库存是否足够等
		// 保存订单
		Order saveOrder = createOrder(userId, stockPrice);
		int result = orderDao.insert(saveOrder);
		if (result < 0) {
			throw new RuntimeException("insertOrder error");
		}
		// 处理订单信息（扣款,扣库存等）
		paymentService.payment(saveOrder);
		return true;
	}

	private Order createOrder(String userId, Long stockPrice) {
		Order saveOrder = new Order();
		saveOrder.setId(DataBase.getDataBaseId(DataBase.OR));
		saveOrder.setOrderNo(genSnHandler.createOrderSn());
		saveOrder.setThreeOrderNo("threeOrderNo");
		saveOrder.setThreeOutOrderNo("threeOutOrderNo");
		saveOrder.setBuyerLogonId(userId);
		saveOrder.setForm("form");
		saveOrder.setApplyId("ApplyId");
		saveOrder.setTotalFee(stockPrice);
		saveOrder.setNotifyStatus("1");
		saveOrder.setStatus("1");
		saveOrder.setCreateBy("TEST用户");
		saveOrder.setCreateTime(new Date());
		saveOrder.setUpdateBy("TEST用户");
		saveOrder.setUpdateTime(new Date());
		return saveOrder;
	}

}
